package mysql

import (
	"code/common/config"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB

func Start() {
	source := config.Config.Database.Source
	StartConfigurableMysql(mysql.Open(source + "?parseTime=True&loc=Local"))
}

func StartConfigurableMysql(dialector gorm.Dialector) {
	db, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		log.Panic(err)
	}
	Db = db

	sqlDb, err := Db.DB()
	if err != nil {
		log.Panic(err)
	}
	sqlDb.SetConnMaxLifetime(time.Minute * 3)
	sqlDb.SetMaxOpenConns(10)
	sqlDb.SetMaxIdleConns(10)

	err = Db.Set("gorm:table_options", "ENGINE=InnoDB").Migrator().AutoMigrate(
		&Answer{},
		&Category{},
		&Problem{},
		&Question{},
	)
	if err != nil {
		log.Panic(err)
	}
}

func Close() {
	sqlDb, err := Db.DB()
	if err != nil {
		log.Panic(err)
	}
	sqlDb.Close()
}
